<template>
  <div>
    <CommonModule
      ref="commonRef"
      v-bind="$attrs"
      showSelectCol
      :columns="columns"
      :fetchList="fetchList"
      :btnsRender="renderBtnsBar"
      :onSelectSelection="onSelectSelection"
    />
    <RejectReasonDialog
      title="驳回原因"
      label="驳回类型"
      :visible.sync="rejectReason.visible"
      :reasonOptions="rejectReason.options"
      :onSubmit="fetchAuditReject"
    />
  </div>
</template>
<script>
import CommonModule from './CommonModule.vue';
import RejectReasonDialog from '@/pages/commodity/components/RejectReasonDialog';
import {
  PRODUCT_INFO_COLUMNS,
  REJECT_REASON_OPTIONS,
} from './constants';
import { getBtnsBar } from '@/utils/getBtnsRender';
import { isResponseSuccess } from '@/utils/bizUtils';
import { isT4Environment } from '@/utils/getUtils';
import {
  getDetailByRecordNoService,
  reviewPassMainService,
  reviewFailMainService
} from '@/api/commodity/commodityAccessManage/commodityAdd';
export default {
  components: {
    CommonModule,
    RejectReasonDialog,
  },
  data () {
    return {
      columns: PRODUCT_INFO_COLUMNS,
      rejectReason: {
        visible: false,
        options: REJECT_REASON_OPTIONS,
      },
      btnLoading: {
        auditSuccess: false,
      }
    }
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h, TableInfo) {
      const btnList = [
        {
          label: '审核驳回',
          method: this.handleAuditReject,
          disabled: TableInfo?.isNullSelection()
        },
        {
          label: '审核通过',
          method: this.handleAuditSuccess,
          disabled: TableInfo?.isNullSelection()
        }
      ]
      // 下次上线前，需要将下面的代码放开
      // return getBtnsBar(h, btnList)
      // 下次上线前，需要将下面的代码删除
      return getBtnsBar(h, isT4Environment() ? btnList : [])
    },
    // 获取表格数据
    async fetchList (data, loadingFn) {
      const res = await getDetailByRecordNoService(data, loadingFn)
      const results = (res?.retData?.results ?? []).map(item => ({
        ...item,
        ...this.getFlatBusiness1(item.business1),
        ..._.pick(item.recordMainDTO, [
          'auditReasonType', 'auditReasonTypeStr',
          'auditReasonNote',
          'auditState', 'auditStateStr',
        ]),
      }))
      return {
        results,
        totalNum: res?.retData?.totalNum
      }
    },
    // 获取扁平化business1字段
    getFlatBusiness1 (business1) {
      const datasource = JSON.parse(business1);
      if (!datasource || Object.keys(datasource).length === 0) { return {} };
      const layersByVal = {
        'SINGLE': '单层',
        'ONE': '一层',
        'TWO': '两层',
        'Three': '三层'
      }
      return _.omit({
        ...datasource,
        packageLayers: layersByVal[datasource.packageLayers] || '', // 包装层数
        ...datasource?.skuPackageDetailDTO, // 包装信息
      }, ['skuPackageDetailDTO'])
    },
    // 审核驳回
    handleAuditReject () {
      this.rejectReason.visible = true
    },
    // 审核通过
    handleAuditSuccess () {
      this.$confirm('确定要审核通过吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.fetchAuditSuccess()
      }).catch(() => {})
    },
    // 请求审核通过
    async fetchAuditSuccess () {
      const TableInfo = this.$refs.commonRef.TableInfo
      const data = {
        recordNo: this.$route?.query?.recordNo,
        spuNos: _.uniq(TableInfo.getAttrs(TableInfo.selection, 'spuNo'))
      }
      const loadingFn = state => { this.btnLoading.auditSuccess = state }
      const res = await reviewPassMainService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('审核通过成功')
        this.$refs.commonRef.getTableData()
      }
    },
    // 请求审核驳回
    async fetchAuditReject (configs) {
      const TableInfo = this.$refs.commonRef.TableInfo
      const data = {
        recordNo: this.$route?.query?.recordNo,
        spuNos: _.uniq(TableInfo.getAttrs(TableInfo.selection, 'spuNo')),
        auditReasonType: configs?.data?.auditReasonType,
        auditReasonNote: configs?.data?.auditReasonNote,
      }
      const res = await reviewFailMainService(data, configs?.loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('审核驳回成功')
        this.$refs.commonRef.getTableData()
        return true
      }
      return false
    },
    // 勾选当前选项
    onSelectSelection (TableInfo, configs) {
      const { refs, row, ischecked } = configs ?? {}
      TableInfo.list.forEach(item => {
        if (item.spuNo == row.spuNo) {
          refs.toggleRowSelection(item, ischecked)
        }
      })
    },
  }
}
</script>
